package com.shd.edanpei.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import com.alibaba.fastjson.JSONObject;
import com.shd.edanpei.R;
import com.shd.edanpei.base.TranBarActivity;
import com.shd.edanpei.base.data.RxBusCode;
import com.shd.edanpei.base.network.ApiConstant;
import com.shd.edanpei.base.network.api.ApiCreator;
import com.shd.edanpei.base.network.exception.ResponeThrowable;
import com.shd.edanpei.base.network.rx.BaseObserver;
import com.shd.edanpei.base.network.rx.RxTransformer;
import com.shd.edanpei.base.rxbus.RxBus;
import com.shd.edanpei.base.rxbus.Subscribe;
import com.shd.edanpei.bean.UrlModel;
import com.shd.edanpei.bean.UserBean;
import com.shd.edanpei.common.Constant;
import com.shd.edanpei.customer.bean.PayInfoModel;
import com.shd.edanpei.db.DaoManager;
import com.shd.edanpei.enums.UrlEnum;
import com.shd.edanpei.presenter.WebMallPresenter;
import com.shd.edanpei.presenter.contract.WebMallContract;
import com.shd.edanpei.util.ToastUtil;
import com.shd.edanpei.util.pay.PayUtils;
import java.net.URLEncoder;
import java.util.HashMap;
import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.alipay.friends.Alipay;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ReflectablePlatformActionListener;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * Created by mc on 2018/3/29.
 * H5页面
 */
public class WebEdpMallActivity extends TranBarActivity<WebMallPresenter> implements WebMallContract.WebIView, ActivityCompat.OnRequestPermissionsResultCallback {

    public static final String TITLE = "title";
    public static final String URL = "url";
    public static final String TYPE = "type";

    @BindView(R.id.headline)
    TextView headline;
    @BindView(R.id.web_view)
    WebView webView;

    private final String INVITE = "share";//分享
    private UrlModel mUrlModel;
    private String mTitle;
    private String mUrl;
    private int mType;
    private ClipboardManager mClipboardManager;
    private  String callback="";

    @Override
    protected int setLayout() {
        return R.layout.activity_edp_mall;
    }

    @Override
    protected WebMallPresenter bindPresenter() {
        return new WebMallPresenter(this);
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        RxBus.get().register(WebEdpMallActivity.this);
        mClipboardManager = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
        String shopUrl=ApiConstant.BASE_DEBUG_MALL_URL_SHOP +DaoManager.getInstance().getUserBean().getMobile()//商城链接
                +"&nickName="+DaoManager.getInstance().getUserBean().getNickName()
                +"&avatarUrl="+URLEncoder.encode(DaoManager.getInstance().getUserBean().getAvatarUrl());
        setUrl(shopUrl);//头像昵称手机号
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

    }


    @Override
    protected void onDestroy() {
        RxBus.get().unRegister(this);
        super.onDestroy();

    }

    @SuppressLint("JavascriptInterface")
    private void setUrl(String url) {
        requestPermission();
        webView=findViewById(R.id.web_view);
        webView.setWebViewClient(new MyWebClient());
        webView.setWebChromeClient(new WebChromeClient());
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.getSettings().setDomStorageEnabled(true);//打开本地缓存提供JS调用,至关重要
        webView.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        //自适应屏幕
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setAllowContentAccess(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setAppCacheEnabled(true);
        webView.getSettings().setAllowFileAccessFromFileURLs(true);
        webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.getSettings().setAppCacheEnabled(false);
        webView.addJavascriptInterface(new JsInterface(), "control");
        webView.getSettings().setBlockNetworkLoads(false);
        webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        webView.loadUrl(url);
        registerForContextMenu(webView);


    }


    /**
     * 获取权限使用的 RequestCode
     */
    private static final int PERMISSIONS_REQUEST_CODE = 1002;

    /**
     * 检查支付宝 SDK 所需的权限，并在必要的时候动态获取。
     * 在 targetSDK = 23 以上，READ_PHONE_STATE 和 WRITE_EXTERNAL_STORAGE 权限需要应用在运行时获取。
     * 如果接入支付宝 SDK 的应用 targetSdk 在 23 以下，可以省略这个步骤。
     */
    private void requestPermission() {
        // Here, thisActivity is the current activity
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this,
                    new String[]{
                            Manifest.permission.READ_PHONE_STATE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE
                    }, PERMISSIONS_REQUEST_CODE);

        }
    }



    @Override
    protected void initListener() {

    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {//如果返回键按下
            //此处写退向后台的处理
            if(webView!=null&&webView.canGoBack()){
                webView.goBack();
            }else{
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(callback.isEmpty())
                    return;
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("resultCode",1);
                String url="javascript:"+callback+"("+jsonObject+")";
                webView.loadUrl(url);
            }
        });

    }

    public class MyWebClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if(Build.VERSION.SDK_INT<26) {
                view.loadUrl(url);
                return true;
            }

            if (url.contains(INVITE)) {
                if (mUrlModel == null) {
                    ApiCreator.getApi().getUrl(UrlEnum.d.getType())
                            .compose(RxTransformer.<UrlModel>errorHandle())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new BaseObserver<UrlModel>() {
                                @Override
                                protected void onSuccess(UrlModel data) {
                                    Bundle bundle = new Bundle();
                                    bundle.putString(Constant.TYPE, Constant.SHARE_URL);
                                    bundle.putParcelable(Constant.DATA, data);
                                    ShareDialogActivity.start(WebEdpMallActivity.this, bundle);
                                }
                                @Override
                                public void onFailure(ResponeThrowable throwable) {
                                    super.onFailure(throwable);
                                    //加载失败

                                }
                            });

                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString(Constant.TYPE, Constant.SHARE_URL);
                    bundle.putParcelable(Constant.DATA, mUrlModel);
                    ShareDialogActivity.start(WebEdpMallActivity.this, bundle);
                }

                return true;
            } else if (url.contains("getmorechance")) {
                RxBus.get().send(RxBusCode.To_PublishFragment);
                finish();
                return true;
            }


            return false;

        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            //webView.loadUrl("javascript:getShareRes("+"'"+1+"'"+")");
//            progressBar.setVisibility(View.GONE);

        }

    }

    @OnClick(R.id.iv_headline_back)
    public void onViewClicked() {
        finish();
    }


    public static void start(Context context, String titile, String url, int type) {
        Bundle bundle = new Bundle();
        bundle.putString(TITLE, titile);
        bundle.putString(URL, url);
        bundle.putInt(TYPE, type);
        Intent intent = new Intent(context, WebEdpMallActivity.class);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    //**<支付成功 - 1 .*/
    //**<支付失败 - 2 .*/
    //**<取消支付 - 3 .*/
    //**<支付异常 - 4 .*/
    /**
     * 支付接口，给H5调用
     */
    public  class JsInterface{
        @JavascriptInterface
        public  void  edpPay(String str){
            final JSONObject object = (JSONObject) JSONObject.parse(str);
            final int type= object.getInteger("type");
             callback= (String) object.get("callback");
            UserBean userEntity =DaoManager.getInstance().getUserBean();
            userEntity.setAccessTokenMall((String)object.get("token"));
            DaoManager.getInstance().saveUserBean(userEntity);
            ApiCreator.getApiMall().edpPayVip(type)
                    .compose(RxTransformer.<PayInfoModel>errorHandleMall())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseObserver<PayInfoModel>() {
                        @Override
                        protected void onSuccess(final PayInfoModel data) {
                            if(data.getCode()==0){
                                if(type==1){
                                    PayUtils.getInstance().aliPay(WebEdpMallActivity.this, data.getAlipay(), new PayUtils.AliPayListener() {
                                        @Override
                                        public void success() {
                                            //支付状态
                                           ToastUtil.showToast("9000");
                                            JSONObject jsonObject=new JSONObject();
                                            jsonObject.put("resultCode",1);
                                            String url="javascript:"+callback+"("+jsonObject+")";
                                            webView.loadUrl(url);
                                        }
                                        @Override
                                        public void failed() {
                                            ToastUtil.showToast(PayUtils.PAY_FAILED);
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    JSONObject jsonObject=new JSONObject();
                                                    jsonObject.put("resultCode",2);
                                                    String url="javascript:"+callback+"("+jsonObject+")";
                                                    webView.loadUrl(url);
                                                }
                                            });
                                        }
                                    });
                                }else{
                                    PayUtils.getInstance().wechatPayMall(WebEdpMallActivity.this, data.getWechat());
                                }
                            }else {
                                JSONObject jsonObject=new JSONObject();
                                jsonObject.put("retCode",data.getCode());
                                webView.loadUrl("javascript:"+callback+"("+jsonObject+")");
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    JSONObject jsonObject=new JSONObject();
                                    jsonObject.put("resultCode",2);
                                    String url="javascript:"+callback+"("+jsonObject+")";
                                    webView.loadUrl(url);
                                }
                            });

                        }});
        }

        //支付后的返回回调
        @Subscribe(code = RxBusCode.WECHAT_PAY_SUCCESS)
        public void weChatPaySuccesst() {
            try{
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("resultCode",1);
                String url="javascript:"+callback+"("+jsonObject+")";
                webView.loadUrl(url);

            }catch (Exception e){

            }
        }

        //支付后的回调
        @Subscribe(code = RxBusCode.WECHAT_PAY_ERROR)
        public void weChatPayERROR() {
            try{
                ToastUtil.showToast("取消回调");
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("resultCode",2);
                String url="javascript:"+callback+"("+jsonObject+")";
                webView.loadUrl(url);
            }catch (Exception e){
                e.printStackTrace();
            }

        }



        @JavascriptInterface
        public  void  edpCopy(String str){
            final JSONObject object = (JSONObject) JSONObject.parse(str);
            String content= (String) object.get("content");
            ClipData clipData = ClipData.newPlainText(null, content);
            // 把数据集设置（复制）到剪贴板
            mClipboardManager.setPrimaryClip(clipData);
        }


        @JavascriptInterface
        public  void cleraFromData(String str){
            ToastUtil.showToast("清除缓存成功");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    webView.clearHistory();
                    webView.clearFormData();
                    deleteDatabase("webview.db");
                    deleteDatabase("webviewCache.db");
                    getCacheDir().delete();
                }
            });


        }

        @JavascriptInterface
        public void viewGoBack(){
                finish();
        }

        /**
         *
         * @param shareObject
         * 1 - QQ
         * 2 - 微信
         * 3 - 朋友圈
         * 4 - 支付宝
         */
        @JavascriptInterface
        public  void  edpShare(String shareObject){
            final JSONObject object = (JSONObject) JSONObject.parse(shareObject);
            //1 成功   2，失败   3取消
            // webView.loadUrl("javascript:getShareRes("+"'"+"{resultCode="+1+"}"+"'"+")");
            int type=object.getInteger("type");
            String logo= (String) object.get("logo");
            String title= (String) object.get("title");
            String content= (String) object.get("content");
            String url= (String) object.get("url");
            callback= (String) object.get("callback");
            if(type==1) {
                showShare(QQ.NAME,logo,title,content,url);
            }else if(type==2){
                showShare(Wechat.NAME,logo,title,content,url);
            }else if(type==3){
                showShare(WechatMoments.NAME,logo,title,content,url);

            }else if(type==4){
                showShare(Alipay.NAME,logo,title,content,url);

            }
        }

    }



    /**
     *
     * @param platform
     * @param logo
     * @param title
     * @param content
     * @param url 分享
     */
    private void showShare(String platform,String logo,String title,String content,String url) {

        OnekeyShare oks = new OnekeyShare();
        oks.disableSSOWhenAuthorize();
        //图片url

        oks.setTitle(title);
        if (platform.equals(QQ.NAME) || platform.equals(Alipay.NAME)) {
            oks.setTitleUrl(url);
        } else {
            oks.setUrl(url);
        }
        oks.setText(content);
        oks.setPlatform(platform);
        oks.setImageUrl(logo);

        //监听分享状态的接口，放到oks.show之前
        oks.setCallback(new ReflectablePlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        Toast.makeText(MobSDK.getContext(), "Share Complete", Toast.LENGTH_SHORT).show();
                        JSONObject jsonObject=new JSONObject();
                        jsonObject.put("state",1);
                        String url="javascript:"+callback+"("+jsonObject+")";
                        webView.loadUrl(url);
                    }
                });
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        Toast.makeText(MobSDK.getContext(), "Share Failure" , Toast.LENGTH_SHORT).show();
                        JSONObject jsonObject=new JSONObject();
                        jsonObject.put("state",2);
                        String url="javascript:"+callback+"("+jsonObject+")";
                        webView.loadUrl(url);
                    }
                });
            }

            @Override
            public void onCancel(Platform platform, int i) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        Toast.makeText(MobSDK.getContext(), "Share onCancel" , Toast.LENGTH_SHORT).show();
                        JSONObject jsonObject=new JSONObject();
                        jsonObject.put("state",3);
                        String url="javascript:"+callback+"("+jsonObject+")";
                        webView.loadUrl(url);
                    }
                });
            }
        });

        oks.show(this);
    }


}
